/**
 * Copyright (c) 2018-present, Chen Guodong
 * All rights reserved.
 *
 * @flow
 */


<template>
  <section class="content">
    <Header title="个人资料">
      <div slot="left" @click="goBack" style="width: 100%;height: 100%;text-align: center;">
        <i class="iconfont icon-arrow-left" style="font-size: 22px"></i>
      </div>
      <div slot="right" @click="saveData" style="width: 100%;height: 100%;text-align: center;">保存</div>
    </Header>
    <div class="main">
      <group label-width="4.5em" label-margin-right="2em" label-align="right" gutter="0">
        <cell title="头像" is-link>
          <div class="avatar" slot="value">
            <img :src="avatar" alt>
            <div class="upload-box">
              <input type="file" accept="image/*" @change="handleFile">
            </div>
          </div>
        </cell>
        <cell title="账户" :value="username"></cell>
        <x-input title="昵称" v-model="nickname" text-align="right"></x-input>
        <popup-picker title="性别" :data="sexlist" v-model="gender" value-text-align="right"></popup-picker>
        <datetime
          title="出生年份"
          start-date="1960-01-01"
          :end-date="endDate"
          v-model="birthday"
          value-text-align="right"
        ></datetime>
        <x-input title="个性签名" v-model="bio" text-align="right"></x-input>
      </group>
    </div>
  </section>
</template>

<script>
import Header from "../../components/Header/Header";
import moment from "moment";
import axios from "axios";
import {
  Group,
  Cell,
  XInput,
  Selector,
  PopupPicker,
  Datetime,
  ChinaAddressData,
  XAddress,
  XTextarea
} from "vux";
import {
  reqUserInfo,
  reqChangeUserInfo,
  reqUploadAvatar
} from "../../api/index.js";
let sextype = ["未设置", "男", "女"];
export default {
  data() {
    return {
      avatar: '', //头像地址
      endDate: moment().format("YYYY-MM-DD"),
      sexlist: [sextype],
      addressData: ChinaAddressData,
      addressValue: ["广东省", "深圳市", "南山区"],
      username: "", //账户
      nickname: "", //昵称
      gender: ["未设置"], //性别
      birthday: "", //出生日期
      bio: "", //个性签名
    };
  },
  mounted() {
    this.initData();
    console.log(
      'moment().format("YYYY-MM-DD"),',
      moment().format("YYYY-MM-DD")
    );
  },
  methods: {
    async handleFile(e) {
      e.preventDefault();
      let self = this;
      const l = JSON.parse(localStorage.getItem("loginInfo"));
      let $target = e.target || e.srcElement;
      let file = $target.files[0];
      let formData = new FormData();
      formData.append("file", file, file.name); //通过append向form对象添加数据
      formData.append("chunk", "0"); //添加form表单中其他数据
      formData.append("token", l.token); //添加form表单中其他数据
      formData.append("appId", "DB000001"); //添加form表单中其他数据
      formData.append("deviceId", "F1EA3FDC-2D5C-519E-AA9F-663E14318683"); //添加form表单中其他数据
      formData.append("appId", "DB000001"); //添加form表单中其他数据
      formData.append("deviceType", "WEB"); //添加form表单中其他数据
      formData.append("timeStamp", "1548773874"); //添加form表单中其他数据
      formData.append("nonceStr", "jBOh6mRAiv3Ohfx1"); //添加form表单中其他数据
      formData.append("signature", "071D48A9CAB1E9AA67860A8824AE75D1"); //添加form表单中其他数据
      let promise = axios.post("/api/member/setavatar", formData, {
        headers: {
          "Content-Type": "multipart/form-data"
        }
      });
      promise
        .then(response => {
          console.log('response', response)
          // 成功回调resolve()
          if (response.data.code === 1) {
            self.avatar = response.data.data.url;
            console.log('self.avatar', self.avatar)
            let loginInfo = JSON.parse(localStorage.loginInfo);
            let newInfo = {...loginInfo, avatar: response.data.data.url};
            console.log('newInfo', newInfo);
            localStorage.setItem("loginInfo", JSON.stringify(newInfo));
            self.$vux.toast.show(`更新头像成功!`);
          } else {
            self.$vux.toast.show(`上传头像失败!`);
          }
        })
        .catch(error => {
          console.log('error', error);
        });
    },
    async initData() {
      let userinfo = JSON.parse(localStorage.getItem("loginInfo"));
      console.log("userinfo", userinfo);
      let result = await reqUserInfo({
        field: "username",
        value: userinfo.username
      });
      if (result.code === 1) {
        this.avatar = result.data.avatar;
        this.nickname = result.data.nickname;
        this.username = result.data.username;
        this.gender = [sextype[result.data.gender]];
        this.birthday = result.data.birthday;
        this.bio = result.data.bio;
        this.avatar = result.data.avatar;
      } else {
        this.$vux.toast.show(`获取用户信息失败:${result.msg}`);
      }
    },
    async saveData() {
      console.log("保存数据");
      let gender = this.gender[0];
      let genderNum = 0;
      if (gender === "未设置") {
        genderNum = 0;
      } else if (gender === "男") {
        genderNum = 1;
      } else {
        genderNum = 2;
      }
      let result = await reqChangeUserInfo({
        nickName: this.nickname,
        avatar: this.avatar,
        bio: this.bio,
        gender: genderNum,
        birthday: this.birthday
      });
      if (result.code === 1) {
        localStorage.setItem("loginInfo", JSON.stringify(result.data));
        this.$vux.toast.show(`修改成功!`);
      } else {
        this.$vux.toast.show(`修改用户信息失败:${result.msg}`);
      }
    },
    goBack() {
      if (window.history.length <= 1) {
        this.$router.push({ path: "/" });
        return false;
      } else {
        this.$router.go(-1);
      }
    }
  },
  components: {
    Header,
    Group,
    Cell,
    XInput,
    PopupPicker,
    XAddress,
    Datetime,
    XTextarea
  }
};
</script>

<style lang='less' scoped>
@import "../../util/theme.less";

.content {
  .be-full();
  .mian {
    width: 100%;
    height: calc(~"100% - 46px");
  }
}

.avatar {
  .mix-flex-center();
  img {
    width: 45px;
    height: 45px;
    border-radius: 45px;
    margin-right: 15px;
  }
  .upload-box {
    opacity: 0;
    position: absolute;
    z-index: 9;
  }
}
</style>
